Imports System.Data.SqlClient

Public Class cls_usuario_

    Implements ICloneable
    Implements IComparer
    Implements IComparable

#Region "Variables ..."
    Private int_idusuario As Integer = 0
    Private str_usuario As String = ""
    Private str_contraseña As String = ""
    Private int_idgrupo As Integer = 0
    Private bit_esroot As Boolean = False
    'Private int_idregistro As Integer = 0
    Private int_idtercero As Integer = 0

    Private obj_tercero As cls_tercero_ = Nothing
    Private obj_grupo As cls_grupo_ = Nothing

    Private col_Items As Collections.Generic.List(Of cls_usuario_) = Nothing
#End Region

    Public Overrides Function ToString() As String
        If Not IsNothing(tercero) Then
            Return tercero.apellido & ", " & tercero.nombres & " (" & usuario & ")"
        Else
            Return usuario
        End If

    End Function

#Region "Propiedades ..."
    ReadOnly Property This
        Get
            Return Me
        End Get
    End Property
    ReadOnly Property ThisDescripcion As String
        Get
            Return Me.ToString
        End Get
    End Property
    ReadOnly Property pKey
        Get
            Return idusuario
        End Get
    End Property
    Property idusuario() As Integer
        Get
            idusuario = int_idusuario
        End Get
        Set(ByVal value As Integer)
            int_idusuario = value
        End Set
    End Property
    Property usuario() As String
        Get
            usuario = str_usuario
        End Get
        Set(ByVal value As String)
            str_usuario = value
        End Set
    End Property
    Property contraseña() As String
        Get
            contraseña = str_contraseña
        End Get
        Set(ByVal value As String)
            str_contraseña = value
        End Set
    End Property
    Property idgrupo() As Integer
        Get
            idgrupo = int_idgrupo
        End Get
        Set(ByVal value As Integer)
            int_idgrupo = value
        End Set
    End Property
    Property esroot() As Boolean
        Get
            esroot = bit_esroot
        End Get
        Set(ByVal value As Boolean)
            bit_esroot = value
        End Set
    End Property
    Property idtercero() As Integer
        Get
            idtercero = int_idtercero
        End Get
        Set(ByVal value As Integer)
            int_idtercero = value
        End Set
    End Property
    Property tercero() As cls_tercero_
        Get
            If IsNothing(obj_tercero) Then
                obj_tercero = New cls_tercero_
                If Not obj_tercero.Buscar(idtercero) Then
                    obj_tercero = Nothing
                End If
            End If
            tercero = obj_tercero
        End Get
        Set(ByVal value As cls_tercero_)
            obj_tercero = value
        End Set
    End Property
    Property grupo() As cls_grupo_
        Get
            If IsNothing(obj_grupo) Then
                obj_grupo = New cls_grupo_
                If Not obj_grupo.Buscar(idgrupo) Then
                    obj_grupo = Nothing
                End If
            End If
            grupo = obj_grupo
        End Get
        Set(ByVal value As cls_grupo_)
            obj_grupo = value
        End Set
    End Property

    ReadOnly Property registro() As cls_registro_
        Get
            registro = Nothing
            If Not IsNothing(tercero) Then
                If Not IsNothing(tercero.registro) Then
                    registro = obj_tercero.registro
                End If
            End If
        End Get
    End Property

    Property Items() As Collections.Generic.List(Of cls_usuario_)
        Get
            Items = col_Items
        End Get
        Set(ByVal value As Collections.Generic.List(Of cls_usuario_))
            col_Items = value
        End Set
    End Property
#End Region

    Private Sub CargarColeccion(ByVal obj_Reader As SqlDataReader)
        col_Items = New Collections.Generic.List(Of cls_usuario_)
        While obj_Reader.Read()
            Dim Elemento As New cls_usuario_
            Elemento.int_idusuario = (obj_Reader.GetValue(obj_Reader.GetOrdinal("idusuario")))

            If IsDBNull(obj_Reader.GetValue(obj_Reader.GetOrdinal("usuario"))) = False Then
                Elemento.str_usuario = (obj_Reader.GetValue(obj_Reader.GetOrdinal("usuario")))
            End If
            If IsDBNull(obj_Reader.GetValue(obj_Reader.GetOrdinal("contraseña"))) = False Then
                Elemento.str_contraseña = DesEncriptarCadena((obj_Reader.GetValue(obj_Reader.GetOrdinal("contraseña"))))
            End If
            If IsDBNull(obj_Reader.GetValue(obj_Reader.GetOrdinal("idgrupo"))) = False Then
                Elemento.int_idgrupo = (obj_Reader.GetValue(obj_Reader.GetOrdinal("idgrupo")))
            End If
            If IsDBNull(obj_Reader.GetValue(obj_Reader.GetOrdinal("esroot"))) = False Then
                Elemento.bit_esroot = (obj_Reader.GetValue(obj_Reader.GetOrdinal("esroot")))
            End If
            If IsDBNull(obj_Reader.GetValue(obj_Reader.GetOrdinal("idtercero"))) = False Then
                Elemento.int_idtercero = (obj_Reader.GetValue(obj_Reader.GetOrdinal("idtercero")))
            End If
            'If IsDBNull(obj_Reader.GetValue(obj_Reader.GetOrdinal("idregistro"))) = False Then
            '    Elemento.int_idregistro = (obj_Reader.GetValue(obj_Reader.GetOrdinal("idregistro")))
            'End If
            col_Items.Add(Elemento)
        End While
    End Sub

    Private Sub CargarVariables(ByVal obj_Reader As SqlDataReader)
        obj_Reader.Read()
        int_idusuario = (obj_Reader.GetValue(obj_Reader.GetOrdinal("idusuario")))

        If IsDBNull(obj_Reader.GetValue(obj_Reader.GetOrdinal("usuario"))) = False Then
            str_usuario = (obj_Reader.GetValue(obj_Reader.GetOrdinal("usuario")))
        End If
        If IsDBNull(obj_Reader.GetValue(obj_Reader.GetOrdinal("contraseña"))) = False Then
            str_contraseña = DesEncriptarCadena((obj_Reader.GetValue(obj_Reader.GetOrdinal("contraseña"))))
        End If
        If IsDBNull(obj_Reader.GetValue(obj_Reader.GetOrdinal("idgrupo"))) = False Then
            int_idgrupo = (obj_Reader.GetValue(obj_Reader.GetOrdinal("idgrupo")))
        End If
        If IsDBNull(obj_Reader.GetValue(obj_Reader.GetOrdinal("esroot"))) = False Then
            bit_esroot = (obj_Reader.GetValue(obj_Reader.GetOrdinal("esroot")))
        End If
        If IsDBNull(obj_Reader.GetValue(obj_Reader.GetOrdinal("idtercero"))) = False Then
            int_idtercero = (obj_Reader.GetValue(obj_Reader.GetOrdinal("idtercero")))
        End If
        'If IsDBNull(obj_Reader.GetValue(obj_Reader.GetOrdinal("idregistro"))) = False Then
        '    int_idregistro = (obj_Reader.GetValue(obj_Reader.GetOrdinal("idregistro")))
        'End If
    End Sub

    Public Function Nuevo(Optional ByVal ObtenerID As Boolean = False) As Boolean
        Nuevo = False
        Dim obj_Conexion As New cls_Conexion
        Try

            'Creacion de Tercero----------------------------------------------------
            'tercero.Nuevo()
            'idtercero = obj_tercero.idtercero
            '-----------------------------------------------------------------------

            obj_Conexion.Conectar()
            With obj_Conexion.obj_SqlCommand
                .CommandType = CommandType.StoredProcedure
                .Connection = obj_Conexion.obj_SqlConnection
                .CommandText = "usuario__Nuevo"
                .Parameters.Add("@usuario", SqlDbType.NVarChar).Value = str_usuario
                .Parameters.Add("@contraseña", SqlDbType.NVarChar).Value = EncriptarCadena(str_contraseña)
                .Parameters.Add("@idgrupo", SqlDbType.Int).Value = int_idgrupo
                .Parameters.Add("@esroot", SqlDbType.Int).Value = bit_esroot
                .Parameters.Add("@idtercero", SqlDbType.Int).Value = IIf(int_idtercero = 0, DBNull.Value, int_idtercero)
                '.Parameters.Add("@idregistro", SqlDbType.Int).Value = int_idregistro
                .ExecuteNonQuery()
            End With
            Nuevo = True
            If ObtenerID Then
                CargarUltimo()
            End If
        Catch ex As SqlClient.SqlException
            Throw New Exception("Error al Crear el registro de usuario_." & Chr(13) & _
           "Por favor informe del siguiente detalle técnico:" & Chr(13) & _
           "Nro de error: " & ex.ErrorCode & "." & Chr(13) & _
           "Descripción: " & ex.Message)
        Finally
            obj_Conexion.Desconectar()
            obj_Conexion = Nothing
        End Try
    End Function

    Public Sub Modificar()
        Dim obj_Conexion As New cls_Conexion
        Try

            'Modificacion de Tercero------------------------------------------------
            If Not IsNothing(obj_tercero) Then
                obj_tercero.registro.Modificar()
            End If
            '-----------------------------------------------------------------------

            obj_Conexion.Conectar()
            With obj_Conexion.obj_SqlCommand
                .CommandType = CommandType.StoredProcedure
                .Connection = obj_Conexion.obj_SqlConnection
                .CommandText = "usuario__Modificar"
                .Parameters.Add("@idusuario", SqlDbType.Int).Value = int_idusuario
                .Parameters.Add("@usuario", SqlDbType.NVarChar).Value = str_usuario
                .Parameters.Add("@contraseña", SqlDbType.NVarChar).Value = EncriptarCadena(str_contraseña)
                .Parameters.Add("@idgrupo", SqlDbType.Int).Value = int_idgrupo
                .Parameters.Add("@esroot", SqlDbType.Int).Value = bit_esroot
                .Parameters.Add("@idtercero", SqlDbType.Int).Value = IIf(int_idtercero = 0, DBNull.Value, int_idtercero)
                ' .Parameters.Add("@idregistro", SqlDbType.Int).Value = int_idregistro
                .ExecuteNonQuery()
            End With
        Catch ex As SqlClient.SqlException
            Throw New Exception("Error al Modificar el registro de usuario_." & Chr(13) & _
           "Por favor informe del siguiente detalle técnico:" & Chr(13) & _
           "Nro de error: " & ex.ErrorCode & "." & Chr(13) & _
           "Descripción: " & ex.Message)
        Finally
            obj_Conexion.Desconectar()
            obj_Conexion = Nothing
        End Try
    End Sub

    Public Sub Eliminar(ByVal idusuario As Integer)
        Dim obj_Conexion As New cls_Conexion
        Try
            obj_Conexion.Conectar()
            With obj_Conexion.obj_SqlCommand
                .CommandType = CommandType.StoredProcedure
                .Connection = obj_Conexion.obj_SqlConnection
                .CommandText = "usuario__Eliminar"
                .Parameters.Add("@idusuario", SqlDbType.Int).Value = idusuario
                .ExecuteNonQuery()
            End With
        Catch ex As SqlClient.SqlException
            Throw New Exception("Error al Eliminar el registro de usuario_." & Chr(13) & _
           "Por favor informe del siguiente detalle técnico:" & Chr(13) & _
           "Nro de error: " & ex.ErrorCode & "." & Chr(13) & _
           "Descripción: " & ex.Message)
        Finally
            obj_Conexion.Desconectar()
            obj_Conexion = Nothing
        End Try
    End Sub

    Public Function Buscar(ByVal idusuario As Integer) As Boolean
        Dim obj_Conexion As New cls_Conexion
        Dim obj_Reader As SqlDataReader
        Try
            Buscar = False
            obj_Conexion.Conectar()
            With obj_Conexion.obj_SqlCommand
                .CommandType = CommandType.StoredProcedure
                .Connection = obj_Conexion.obj_SqlConnection
                .CommandText = "usuario__Buscar"
                .Parameters.Add("@idusuario", SqlDbType.Int).Value = idusuario
            End With
            obj_Reader = obj_Conexion.obj_SqlCommand.ExecuteReader
            If obj_Reader.HasRows Then
                CargarVariables(obj_Reader)
                Buscar = True
            End If
        Catch ex As SqlClient.SqlException
            Throw New Exception("Error al Buscar el registro de usuario_." & Chr(13) & _
           "Por favor informe del siguiente detalle técnico:" & Chr(13) & _
           "Nro de error: " & ex.ErrorCode & "." & Chr(13) & _
           "Descripción: " & ex.Message)
        Finally
            obj_Conexion.Desconectar()
            obj_Conexion = Nothing
            obj_Reader = Nothing
        End Try
    End Function

    Public Sub CargarUltimo()
        Dim obj_Conexion As New cls_Conexion
        Dim obj_Reader As SqlDataReader
        Try
            obj_Conexion.Conectar()
            With obj_Conexion.obj_SqlCommand
                .CommandType = CommandType.StoredProcedure
                .Connection = obj_Conexion.obj_SqlConnection
                .CommandText = "usuario__CargarUltimo"
            End With
            obj_Reader = obj_Conexion.obj_SqlCommand.ExecuteReader
            If obj_Reader.HasRows Then
                CargarVariables(obj_Reader)
            End If
        Catch ex As SqlClient.SqlException
            Throw New Exception("Error al CargarUltimo registro de usuario_." & Chr(13) & _
           "Por favor informe del siguiente detalle técnico:" & Chr(13) & _
           "Nro de error: " & ex.ErrorCode & "." & Chr(13) & _
           "Descripción: " & ex.Message)
        Finally
            obj_Conexion.Desconectar()
            obj_Conexion = Nothing
            obj_Reader = Nothing
        End Try
    End Sub

    Public Function CargarTodos(Optional ByVal idregistroestado As Integer = 1) As Boolean
        Dim obj_Conexion As New cls_Conexion
        Dim obj_Reader As SqlDataReader
        Try
            CargarTodos = False
            obj_Conexion.Conectar()
            With obj_Conexion.obj_SqlCommand
                .CommandType = CommandType.StoredProcedure
                .Connection = obj_Conexion.obj_SqlConnection
                .CommandText = "usuario__CargarTodos"
                .Parameters.Add("@idregistroestado", SqlDbType.Int).Value = idregistroestado
            End With
            obj_Reader = obj_Conexion.obj_SqlCommand.ExecuteReader
            If obj_Reader.HasRows Then
                CargarColeccion(obj_Reader)
                CargarTodos = True
            End If
        Catch ex As SqlClient.SqlException
            Throw New Exception("Error al CargarTodos los registros de usuario_." & Chr(13) & _
           "Por favor informe del siguiente detalle técnico:" & Chr(13) & _
           "Nro de error: " & ex.ErrorCode & "." & Chr(13) & _
           "Descripción: " & ex.Message)
        Finally
            obj_Conexion.Desconectar()
            obj_Conexion = Nothing
            obj_Reader = Nothing
        End Try
    End Function

    Public Function CargarXidgrupo(ByVal idgrupo As Integer) As Boolean
        Dim obj_Conexion As New cls_Conexion
        Dim obj_Reader As SqlDataReader
        Try
            CargarXidgrupo = False
            obj_Conexion.Conectar()
            With obj_Conexion.obj_SqlCommand
                .CommandType = CommandType.StoredProcedure
                .Connection = obj_Conexion.obj_SqlConnection
                .CommandText = "usuario__CargarXidgrupo"
                .Parameters.Add("@idgrupo", SqlDbType.Int).Value = idgrupo
            End With
            obj_Reader = obj_Conexion.obj_SqlCommand.ExecuteReader
            If obj_Reader.HasRows Then
                CargarColeccion(obj_Reader)
                CargarXidgrupo = True
            End If
        Catch ex As SqlClient.SqlException
            Throw New Exception("Error al CargarXidgrupo los registros de usuario_." & Chr(13) & _
           "Por favor informe del siguiente detalle técnico:" & Chr(13) & _
           "Nro de error: " & ex.ErrorCode & "." & Chr(13) & _
           "Descripción: " & ex.Message)
        Finally
            obj_Conexion.Desconectar()
            obj_Conexion = Nothing
            obj_Reader = Nothing
        End Try
    End Function
    Public Function CargarXtercerotipo(ByVal tipo As cls_tercero_.enu_tipotercero) As Boolean
        Dim obj_Conexion As New cls_Conexion
        Dim obj_Reader As SqlDataReader
        Try
            CargarXtercerotipo = False
            obj_Conexion.Conectar()
            With obj_Conexion.obj_SqlCommand
                .CommandType = CommandType.StoredProcedure
                .Connection = obj_Conexion.obj_SqlConnection
                .CommandText = "usuario__CargarXtercerotipo"
                .Parameters.Add("@tipo", SqlDbType.Int).Value = tipo
            End With
            obj_Reader = obj_Conexion.obj_SqlCommand.ExecuteReader
            If obj_Reader.HasRows Then
                CargarColeccion(obj_Reader)
                CargarXtercerotipo = True
            End If
        Catch ex As SqlClient.SqlException
            Throw New Exception("Error al CargarXtercerotipo los registros de usuario_." & Chr(13) & _
           "Por favor informe del siguiente detalle técnico:" & Chr(13) & _
           "Nro de error: " & ex.ErrorCode & "." & Chr(13) & _
           "Descripción: " & ex.Message)
        Finally
            obj_Conexion.Desconectar()
            obj_Conexion = Nothing
            obj_Reader = Nothing
        End Try
    End Function
    Public Function CargarXidtercero(ByVal idtercero As Integer) As Boolean
        Dim obj_Conexion As New cls_Conexion
        Dim obj_Reader As SqlDataReader
        Try
            CargarXidtercero = False
            obj_Conexion.Conectar()
            With obj_Conexion.obj_SqlCommand
                .CommandType = CommandType.StoredProcedure
                .Connection = obj_Conexion.obj_SqlConnection
                .CommandText = "usuario__CargarXidtercero"
                .Parameters.Add("@idtercero", SqlDbType.Int).Value = idtercero
            End With
            obj_Reader = obj_Conexion.obj_SqlCommand.ExecuteReader
            If obj_Reader.HasRows Then
                CargarColeccion(obj_Reader)
                CargarXidtercero = True
            End If
        Catch ex As SqlClient.SqlException
            Throw New Exception("Error al CargarXidtercero los registros de usuario_." & Chr(13) & _
           "Por favor informe del siguiente detalle técnico:" & Chr(13) & _
           "Nro de error: " & ex.ErrorCode & "." & Chr(13) & _
           "Descripción: " & ex.Message)
        Finally
            obj_Conexion.Desconectar()
            obj_Conexion = Nothing
            obj_Reader = Nothing
        End Try
    End Function

    Public Function BuscarXusuarioXcontraseña(ByVal usuario As String, ByVal contraseña As String) As Boolean
        Dim obj_Conexion As New cls_Conexion
        Dim obj_Reader As SqlDataReader
        Try
            BuscarXusuarioXcontraseña = False
            obj_Conexion.Conectar()
            With obj_Conexion.obj_SqlCommand
                .CommandType = CommandType.StoredProcedure
                .Connection = obj_Conexion.obj_SqlConnection
                .CommandText = "usuario__BuscarXusuarioXcontraseña"
                .Parameters.Add("@usuario", SqlDbType.NVarChar).Value = usuario
                .Parameters.Add("@contraseña", SqlDbType.NVarChar).Value = EncriptarCadena(contraseña)
            End With
            obj_Reader = obj_Conexion.obj_SqlCommand.ExecuteReader
            If obj_Reader.HasRows Then
                CargarVariables(obj_Reader)
                BuscarXusuarioXcontraseña = True
            End If
        Catch ex As SqlClient.SqlException
            Throw New Exception("Error al BuscarXusuarioXcontraseña el registro de usuario_." & Chr(13) & _
          "Por favor informe del siguiente detalle técnico:" & Chr(13) & _
          "Nro de error: " & ex.ErrorCode & "." & Chr(13) & _
          "Descripción: " & ex.Message)
        Finally
            obj_Conexion.Desconectar()
            obj_Conexion = Nothing
            obj_Reader = Nothing
        End Try
    End Function

    Public Function BuscarXusuario(ByVal usuario As String) As Boolean
        Dim obj_Conexion As New cls_Conexion
        Dim obj_Reader As SqlDataReader
        Try
            BuscarXusuario = False
            obj_Conexion.Conectar()
            With obj_Conexion.obj_SqlCommand
                .CommandType = CommandType.StoredProcedure
                .Connection = obj_Conexion.obj_SqlConnection
                .CommandText = "usuario__BuscarXusuario"
                .Parameters.Add("@usuario", SqlDbType.NVarChar).Value = usuario
            End With
            obj_Reader = obj_Conexion.obj_SqlCommand.ExecuteReader
            If obj_Reader.HasRows Then
                CargarVariables(obj_Reader)
                BuscarXusuario = True
            End If
        Catch ex As SqlClient.SqlException
            Throw New Exception("Error al BuscarXusuario el registro de usuario_." & Chr(13) & _
          "Por favor informe del siguiente detalle técnico:" & Chr(13) & _
          "Nro de error: " & ex.ErrorCode & "." & Chr(13) & _
          "Descripción: " & ex.Message)
        Finally
            obj_Conexion.Desconectar()
            obj_Conexion = Nothing
            obj_Reader = Nothing
        End Try
    End Function

#Region "Encriptado Contraseña..."
    Private Patron_busqueda As String = "aYbcdSDeFGfg34QHUThIiAjJkOlM1RW5KmZnNño6pE2LXqr7s8C9t0uvPwVBÑxyz"
    Private Patron_encripta As String = "QWlaEñ1mRkpTYUIjn2qsOhPioÑ78Lb3K90g6wdJHGF4uDvfySe5AZXCxVrBtzNcM"
    'Los patrones están aquí sin terminar por falta de espacio.

    Private Function EncriptarCadena(ByVal cadena As String) As String
        Dim idx As Integer
        Dim result As String = ""
        For idx = 0 To cadena.Length - 1
            result += EncriptarCaracter(cadena.Substring(idx, 1), cadena.Length, idx)
        Next
        Return result
    End Function

    Private Function EncriptarCaracter(ByVal caracter As String, ByVal variable As Integer, ByVal a_indice As Integer) As String
        Dim caracterEncriptado As String = "", indice As Integer
        If Patron_busqueda.IndexOf(caracter) <> -1 Then
            indice = (Patron_busqueda.IndexOf(caracter) + variable + a_indice) Mod Patron_busqueda.Length
            Return Patron_encripta.Substring(indice, 1)
        End If
        Return caracter
    End Function

    Private Function DesEncriptarCadena(ByVal cadena As String) As String
        Dim idx As Integer
        Dim result As String = ""
        For idx = 0 To cadena.Length - 1
            result += DesEncriptarCaracter(cadena.Substring(idx, 1), cadena.Length, idx)
        Next
        Return result
    End Function

    Private Function DesEncriptarCaracter(ByVal caracter As String, ByVal variable As Integer, ByVal a_indice As Integer) As String
        Dim indice As Integer
        If Patron_encripta.IndexOf(caracter) <> -1 Then
            If (Patron_encripta.IndexOf(caracter) - variable - a_indice) > 0 Then
                indice = (Patron_encripta.IndexOf(caracter) - variable - a_indice) Mod Patron_encripta.Length
            Else
                indice = (Patron_busqueda.Length) + ((Patron_encripta.IndexOf(caracter) - variable - a_indice) Mod Patron_encripta.Length)
            End If
            indice = indice Mod Patron_encripta.Length
            Return Patron_busqueda.Substring(indice, 1)
        Else
            Return caracter
        End If
    End Function
#End Region

    Public Function Clone() As Object Implements System.ICloneable.Clone
        Dim obj_usuario_Clon As New cls_usuario_
        obj_usuario_Clon.int_idusuario = Me.int_idusuario
        obj_usuario_Clon.str_usuario = Me.str_usuario
        obj_usuario_Clon.str_contraseña = Me.str_contraseña
        obj_usuario_Clon.int_idgrupo = Me.int_idgrupo
        obj_usuario_Clon.bit_esroot = Me.bit_esroot
        obj_usuario_Clon.int_idtercero = Me.int_idtercero
        ' obj_usuario_Clon.int_idregistro = Me.int_idregistro
        obj_usuario_Clon.col_Items = Me.col_Items
        Return obj_usuario_Clon
    End Function

    Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare
        Return CType(x, cls_usuario_).idusuario.CompareTo(CType(y, cls_usuario_).idusuario)
    End Function

    Public Function CompareTo(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo
        Return CType(obj, cls_usuario_).idusuario.CompareTo(Me.idusuario)
    End Function
End Class
